from utils.AuthV3Util import addAuthParams
from text import correct_markdown_syntax, occupy_text, markdown_text2

import requests
import configparser
import json
import os

# 读取配置文件
config = configparser.ConfigParser()
script_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(script_dir, 'config.ini')
config.read(config_path)

# 从配置文件中获取 API 密钥
access_key_id = config.get('YoudaoCloud', 'access_key_id')
access_key_secret = config.get('YoudaoCloud', 'access_key_secret')

def youdao_translate(text):
    '''
    note: 将下列变量替换为需要请求的参数
    '''
    lang_from = 'en'
    lang_to = 'zh'
    vocab_id = '您的用户词表ID'

    data = {'q': text, 'from': lang_from, 'to': lang_to, 'vocabId': vocab_id}

    addAuthParams(access_key_id, access_key_secret, data)

    header = {'Content-Type': 'application/x-www-form-urlencoded'}
    res = doCall('https://openapi.youdao.com/api', header, data, 'post')
    # print(str(res.content, 'utf-8'))
    # 转为json，打印其中的translation字段
    res = json.loads(str(res.content, 'utf-8'))
    res = res.get("translation")
    return res[0]


def doCall(url, header, params, method):
    if 'get' == method:
        return requests.get(url, params)
    elif 'post' == method:
        return requests.post(url, params, header)


if __name__ == "__main__":
    # 使用 <ALIMT > 和 </ALIMT> 包裹的文本不会被翻译
    # print(translate("For further reading on the core concepts of LangChain, we've got detailed <ALIMT > PROTECTED_0 </ALIMT>"))

    text, placeholder_dict = occupy_text(markdown_text2)
    print(text)
    print(youdao_translate(text))